const Actions = require('./actions');
const DB = require('app/db.js');
import { guid, getTime, getMarkdownText, sendNotice } from 'clientConfig/util/queryurlfield';
const monStorage = require('clientConfig/util/StoreData').monStorage;
const Storage = require('clientConfig/util/StoreData').Storage;
const { Toast } = SaltUI;
import { Control } from 'react-keeper';

let form_component_values = null;
module.exports = Reflux.createStore({
    listenables: [Actions],
    data: {

    },

    onFetch: function (params, cb) {
        let t = this
        DB.Approval.get_approval_detail({ process_id: params }).then((content) => {
            if (content.status != 8) {
                Toast.show({
                    type: "error",
                    content: "该单号还未通过审批"
                })
            } else {
                var pagedata_fallut = {};
                pagedata_fallut.proName = content.proj_name;
                pagedata_fallut.proNum = content.proj_num;
                pagedata_fallut.webhook = content.proj_webhook;
                t.data.pagedata_fallut = pagedata_fallut;
                t.updateComponent();
            }
        }).catch((error) => { // 失败 or 有异常被捕获
            Toast.show({
                type: "error",
                content: error.message
            })
            // var pagedata_fallut = {};
            // pagedata_fallut.proName = '';
            // pagedata_fallut.proNum = ''
            // pagedata_fallut.webhook = '';
            // t.data.pagedata_fallut = pagedata_fallut;
            // t.updateComponent();
        });
    },
    onSendForm: function (params, contents, boo) {
        let t = this;
        let agent_id = Storage.get('user.agentid');
        let create_time = getTime();
        let finish_time = "";
        let originator_user = monStorage.get('user.nickname');
        let originator_user_id = monStorage.get('user.id'); //审批发起人的userid
        let dept_id = monStorage.get('user.department');
        let approvers = contents.spr;
        let approvers_id = contents.approvers_id;
        let cc_list = contents.csr;
        let cc_list_id = contents.cc_list_id;
        var array = [];
        if (approvers instanceof Array) {
            for (let i = 0; i < approvers.length; i++) {
                array.push(JSON.stringify({ content: "", file: "", imgae: "" }));
            }
        }
        let process_result = array.length > 1 ? array : JSON.stringify({ content: "", file: "", imgae: "" });
        let next_cursor = 0;
        const status = 1;
        const module_type = "maintenance";
        const proj_category = !boo ? "faultarrange" : "changereq";
        const proj_num = params.data.proNum;
        const proj_name = params.data.proName;
        const proj_webhook = params.data.proj_webhook;
        const proj_falutNum = params.data.proj_falutNum;
        const proj_markdown = getMarkdownText({ create_time, originator_user, approvers, proj_name, proj_num, status, title: "维护安排" })
        const process_id = guid();
        var nodelists = [];
        let node_info = [];
        for (let i = 0; i < params.node.length; i++) {
            var obj = {}
            if (params.node[i].name == "上传附件" || params.node[i].name == "上传图片") {
                obj.value = JSON.stringify(params.data[params.node[i].formOption]);
            } else {
                obj.value = params.data[params.node[i].formOption];
            }
            obj.name = params.node[i].name;
            node_info.push(obj);
        }
        var obj = {}
        obj.node_info = node_info
        Object.assign(obj, { node_name: !boo ? "faultarrange" : "changereq", modified: !boo ? 0 : 1, permission: "1" })
        nodelists.push(obj);
        form_component_values = {
            content: { proj_create_time: getTime() },
            nodelists: nodelists
        };
        var send = Object.assign({}, { agent_id, create_time, finish_time, originator_user, originator_user_id, dept_id, approvers, approvers_id, cc_list, cc_list_id, process_result, next_cursor, status, module_type, proj_category, proj_num, proj_name, proj_webhook, proj_markdown, proj_falutNum, process_id, form_component_values })
        // console.log(send)
        if (params.pagedata) {
            send = this.modify(send, params);
            //console.log(send)
        }
        let notice_info = {
            "process_id": process_id,
            "no_read": true,
            "proj_num": proj_num,
            "proj_name": proj_name,
            "create_time": create_time,
            "status": status,
            "type": "待我审批的"
        }
        let noticed_lists = approvers_id instanceof Array ? approvers_id[next_cursor] : approvers_id;
        DB.Approval.send_approval(send)
            .then((content) => { // 成功
                Toast.show({
                    type: 'success',
                    content: "提交成功",
                });
                sendNotice(noticed_lists, notice_info)
                Control.go(-1)
            })
            .catch((error) => { // 失败 or 有异常被捕获
                if (error.message) {
                    Toast.show({
                        type: 'error',
                        content: error.message
                    });
                } else {
                    Toast.show({
                        type: 'error',
                        content: '提交失败'
                    });
                }
            });
    },
    modify: function (new_data, old_data) {
        let edit = old_data.edit;
        old_data = old_data.pagedata;
        let old_change = [];//变更前字段 发送群消息
        let new_change = [];//变更后字段 发送群消息
        let form_component_values_new = new_data.form_component_values;
        let nodelists_new = form_component_values_new.nodelists;
        for (let i = 0; i < nodelists_new.length; i++) {
            let node_info_new = nodelists_new[i].node_info;
            let node_info_old = old_data.node_info;
            for (let j = 0; j < node_info_new.length; j++) {
                if (node_info_new[j].value != node_info_old[j].value) {
                    node_info_new[j].ext_value = node_info_old[j].value//变更过
                    old_change.push(node_info_old[j].value);
                    new_change.push(node_info_new[j].value);
                }
            }
        }
        form_component_values_new.nodelists = nodelists_new;
        form_component_values_new.content.changerecord_type = JSON.stringify({
            type: edit ? "撤销申请" : "内容变更",
            old_process_id: old_data.process_id
        })
        new_data.form_component_values = form_component_values_new;
        let { create_time, originator_user, approvers, approvers_id, next_cursor, proj_name, proj_num, status } = { ...new_data };
        const proj_markdown = getMarkdownText({ old_change, new_change, change_type: edit ? "撤销申请" : "内容变更", create_time, originator_user, approvers: approvers[next_cursor], proj_name, proj_num, status, title: '维护支持' }, "change")
        new_data.proj_markdown = proj_markdown;
        return new_data;
    },


    updateComponent: function () {
        this.trigger(this.data);
    },

    getInitialState: function () {
        return this.data;
    }
});
